package cz.swosh.stomp.web;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import cz.swosh.stomp.ejb.*;

/**
 * <p/>
 * Created by IntelliJ IDEA.
 * User: zslajchrt
 * Date: Mar 15, 2010
 * Time: 3:17:43 PM
 */
public class PhotoServlet extends HttpServlet {

    @EJB
    PersonDAO personDAO;

    @Override
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
            throws ServletException, IOException {

        // getPathInfo() vrací 'ocásek' URI, tj.
        // část, která následuje za částí, na kterou
        // je přilepen servlet.
        // Mapování: /photo/*
        // Extrakce: /photo/<nazevFotky> -> /<nazevFotky>
        String pathInfo = request.getPathInfo();
        if (pathInfo == null) {
            throw new ServletException("No photo specified");
        }
        // Odstraníme '/'
        int id = Integer.parseInt(pathInfo.substring(2));
        Person person = personDAO.getPerson(id);

        // Pošleme obrázek na klienta.
        byte[] image = person.getImage();
        ServletOutputStream output = response.getOutputStream();
        output.write(image);
        output.flush();
    }
}
